<template>
  <div class="qrcodeList">
    <el-row>
      <el-col :span="5">
        <el-tree :data="classData"
                 :props="defaultProps"
                 @node-click="handleNodeClick"></el-tree>
      </el-col>
      <el-col :span="19"
              id="loading">
        <el-form label-width="80px">
          <el-col :span="12">
            <el-form-item label="查询字段">
              <div class="searchName">
                <el-select v-model="requestParam.search_field"
                           disabled
                           placeholder="请选择查询字段">
                  <el-option v-for="item in searchOptions"
                             :key="item.field"
                             :label="item.field_name"
                             :value="item.field">
                  </el-option>
                </el-select>
                <el-input v-model="requestParam.search_value"></el-input>
              </div>

            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="查询时间">
              <el-date-picker v-model="timeVal"
                              type="daterange"
                              range-separator="至"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              :default-time="['00:00:00', '23:59:59']">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-button type="primary"
                       @click="uoloadEnter">下载录入码</el-button>
            <el-button type="primary"
                       @click="uoloadAll">下载全部</el-button>
            <el-button type="primary"
                       @click="printAll">打印全部</el-button>
          </el-col>
          <el-col :span="12"
                  class="flex-end">
            <el-button type="primary"
                       @click="search">查询</el-button>
            <el-button @click="reset">重置</el-button>
          </el-col>
        </el-form>
        <el-col :span="24">
          <el-table :data="tableData.list"
                    :header-cell-style="{background:'#f5f5f5'}"
                    border>
            <el-table-column type="index"
                             label="序号"
                             width="50">
            </el-table-column>
            <el-table-column property="bus_name"
                             label="所属业务"></el-table-column>
            <el-table-column property="content"
                             label="码内信息"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text"
                           @click="upload(scope.row)">下载</el-button>
                <el-button type="text"
                           @click="print(scope.row)">打印</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination @size-change="handleSizeChange"
                         @current-change="handleCurrentChange"
                         :current-page="requestParam.page"
                         :page-sizes="[10, 20, 30]"
                         :page-size="requestParam.page_size"
                         layout="total, sizes, prev, pager, next, jumper"
                         :total="tableData.total_count">
          </el-pagination>
        </el-col>
      </el-col>
    </el-row>
    <!-- 打印的内容 -->
    <div class="print-div"
         ref="print">
      <div class="printCon">
        <div class="printBox">
          <img :src="codeUrl"
               alt="">
        </div>
      </div>
    </div>
    <!-- 打印全部内容 -->
    <div class="print-all"
         ref="printAll">
      <div class="printCon">
        <div class="printBox"
             v-for="(item,index) in urlArr"
             :key="index">
          <img :src="item"
               alt="">
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { QrcodeListApi } from '@/services/ResourceCentre'
import { standardCodeApi } from "@/services/StandardCode";

export default {
  data () {
    return {
      tableData: {
        list: [],
        total_count: 0
      },
      requestParam: {
        bus_id: '',
        // project_id: '',
        search_field: '',
        search_value: '',
        start_time: '',
        end_time: '',
        is_page: 1,
        page: 1,
        page_size: 10
      },
      resetParam: {
        // search_field: '',
        search_value: '',
        start_time: '',
        end_time: '',
        is_page: 1,
        page: 1,
        page_size: 10
      },
      enterParams: { //下载录入码
        qrcode_type: '2',
        bus_id: '',
        qrcode_title: '',
        qrcode_name: ''
      },
      allParams: { //下载全部
        bus_id: '',
        search_field: '',
        search_value: '',
        start_time: '',
        end_time: ''
      },
      timeVal: '',
      searchOptions: [],
      oneParams: {}, //下载单个二维码
      value: '',
      value1: '',
      codeUrl: '',
      classData: [],
      defaultProps: {
        children: 'children',
        label: 'cate_name'
      },
      urlArr: [],
      times: 0,
      timeZip: 0
    }
  },
  created () {
    this.getClass()
    // this.getTypeCode()

    // let store = this.$store.state.choosedProject
    // let local = window.localStorage.getItem('choosedProject') || '{}'
    // this.choosedProject = store.project_id ? store : JSON.parse(local)
    // this.requestParam.project_id = this.choosedProject.project_id
  },
  mounted () { },
  methods: {
    //标准码
    getTypeCode () {
      return standardCodeApi.getConsoleStandardCode({
        params: {
          code_type: 'qrcodeType',
          is_page: 0
        }
      }).then((res) => {
        if (res.code == 0) {
          this.searchOptions = res.data.list;
          console.log(this.searchOptions, '233333');
        }
      }).catch((error) => {
        console.log(error)
      });
    },
    //分类列表
    getClass () {
      QrcodeListApi.getclassList({
        params: {
          is_page: 0
        }
      }).then(res => {
        this.classData = res.data.list
        this.classData.forEach(item => {
          item.children.forEach(names => {
            names.cate_name = names.bus_name
          })
        })
      }).catch(err => {
        console.log(err);
      })
    },
    handleNodeClick (data) {
      if (data.bus_id) {
        this.requestParam.bus_id = data.bus_id
        this.classData.forEach(item => {
          item.children.forEach(names => {
            if (data.bus_id === names.bus_id) {
              this.searchOptions = names.search_field
              this.requestParam.search_field = this.searchOptions[0].field
            }
          })
        })
        this.search()
        this.isJoin = false
      }
    },
    //获取下载列表
    search () {
      this.requestParam.start_time = this.timeVal[0]
      this.requestParam.end_time = this.timeVal[1]
      QrcodeListApi.getuploadList({
        params: this.requestParam
      }).then(res => {
        this.tableData = res.data
      }).catch(err => {
        console.log(err);
      })
    },
    reset () {
      let reset = JSON.parse(JSON.stringify(this.resetParam))
      this.requestParam = Object.assign(this.requestParam, reset)
      this.timeVal = ''
      this.search()
    },
    handleSizeChange (val) {
      this.requestParam.page_size = val
      this.search()
    },
    handleCurrentChange (val) {
      this.requestParam.page = val
      this.search()
    },
    //获取图片地址
    getUrl (row) {
      let obj = {
        check_item_id: row.check_item_id,
        primary_key: row.primary_key,
        primary_key_value: row.primary_key_value,
        qrcode_type: row.qrcode_type,
        bus_name: row.bus_name,
        preview_content: row.preview_content,
        qrcode_title: '',
        qrcode_name: ''
      }
      this.oneParams = obj
      QrcodeListApi.uploadOnecode({
        params: this.oneParams
      }).then(res => {
        if (res.code === 0) {
          this.codeUrl = res.data.qrcode_url
        }
      }).catch(err => {
        console.log(err);
      })
    },
    //下载单个
    upload (row) {
      this.getUrl(row)
      setTimeout(() => {
        var alink = document.createElement("a");
        alink.href = this.codeUrl + "?response-content-type=application/octet-stream";//直接下载
        // alink.href = this.codeUrl; //打开预览下载
        alink.target = "_blank";
        alink.download = "二维码"; //文件名
        alink.click();
      }, 500)
    },
    //打印
    print (row) {
      this.getUrl(row)
      var that = this
      setTimeout(() => {
        that.$print(that.$refs.print)
      }, 1000);
    },
    //打印全部
    printAll () {
      this.getAllUrl()
    },
    //下载录入码
    uoloadEnter () {
      this.enterParams.bus_id = this.requestParam.bus_id
      QrcodeListApi.uploadEnterCode({
        params: this.enterParams
      }).then(res => {
        if (res.code === 0) {
          var alink = document.createElement("a");
          alink.href = res.data.qrcode_url + "?response-content-type=application/octet-stream";//直接下载
          // alink.href = this.codeUrl; //打开预览下载
          alink.target = "_blank";
          alink.download = "二维码"; //文件名
          alink.click();
        }
      }).catch(err => {
        console.log(err);
      })
    },
    //获取打印图片地址
    getAllUrl () {
      this.allParams.bus_id = this.requestParam.bus_id
      QrcodeListApi.uploadUrl({
        params: this.allParams
      }).then(res => {
        if (res.code === 0) {
          this.urlArr = res.data.list
          var that = this
          setTimeout(() => {
            that.$print(that.$refs.printAll)
          }, 1000);
        }
      }).catch(err => {
        console.log(err);
      })
    },
    //加载中
    // startLoading () {
    //   const loading = this.$loading({
    //     lock: true,//lock的修改符--默认是false
    //     text: '拼命下载中',//显示在加载图标下方的加载文案
    //     spinner: 'el-icon-loading',//自定义加载图标类名
    //     background: 'rgba(0, 0, 0, 0.7)',//遮罩层颜色
    //     target: document.querySelector('#loading')//loadin覆盖的dom元素节点
    //   });
    //   return loading
    // },
    //关闭弹窗
    // endLoading (loading) {
    //   loading.close();
    // },
    //下载全部
    uoloadAll () {
      this.allParams.bus_id = this.requestParam.bus_id
      if (this.allParams.bus_id === '') {
        this.$message.warning('请先选择业务名称')
      } else {
        // this.getCode()
        //首次加入下载列表后,再点击下载全部就只调取获取压缩包接口
        //下载压缩包成功后,点击下载全部重新加入下载列表
        if (this.isJoin) {
          //下载
          this.getZip()
        } else {
          //加入列表
          this.getCode()
        }
      }
    },
    //加入下载列表
    getCode () {
      QrcodeListApi.uploadAll({
        params: this.allParams
      }).then(res => {
        // this.startLoading()
        if (res.code === 0) {
          this.isJoin = true
          //延迟两秒调取
          var time = setInterval(() => {
            this.getZip()
          }, 2000);
          this.times = time
        }
      }).catch(err => {
        console.log(err);
      })
    },
    //获取二维码压缩包
    getZip () {
      QrcodeListApi.uploadCode({
        params: {
          bus_id: this.allParams.bus_id
        }
      }).then(res => {
        if (res.code === 0) {
          clearInterval(this.times)
          clearInterval(this.timeZip)
          // this.endLoading(this.startLoading()); // 关闭loading
          this.isJoin = false
          let url = res.data.qrcode_url
          var alink = document.createElement('a')
          alink.href = url
          alink.target = '_blank'
          alink.download = ''
          alink.click()
        } else {
          //下载失败
          // this.join = true
          // var timeZip = setInterval(() => {
          //   this.uoloadAll()
          // }, 5000);
          // this.timeZip = timeZip
          // console.log(res.msg, '3333333333');
        }
      }).catch(err => {
        console.log(err);
      })
    }
  },
  computed: {},
  watch: {
    // '$store.state.choosedProject.project_id': function (val) {
    //   this.requestParam.project_id = val;
    // },
  }
}
</script>

<style lang="scss" scoped>
@media print {
  .print-div {
    img {
      width: 600px;
      height: 400px;
      margin-right: 10px;
    }
  }
  .print-all {
    .printCon {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-around;
    }
    .printBox {
      display: flex;
      justify-content: space-between;
      padding-top: 30px;
      margin-top: 100px;
      img {
        width: 300px;
        height: 200px;
        margin-right: 10px;
      }
      p {
        font-size: 15px;
        line-height: 30px;
      }
    }
  }
}
.qrcodeList {
  padding: 20px;
  .el-select {
    width: 40%;
  }
  .el-input {
    width: 60%;
    margin-left: 10px;
  }
  .el-date-editor--daterange {
    width: 100%;
  }
  .searchName {
    display: flex;
  }
  .el-table {
    margin-top: 20px;
  }
  .print-div {
    display: none;
  }
  .print-all {
    display: none;
  }
}
</style>